﻿using System;
using System.Text;
using System.Web;
using Sissonix.ExtRest.Serialization;


namespace Sissonix.ExtRest.RestManager.Processors
{
    /// <summary>
    /// Summary description for ProcessorHelper
    /// </summary>
    public class ProcessorHelper
    {
        public static object GetDeserializedObjectFromRequestStream(HttpContext context, Type deserializeAsType)
        {
            string parsedContentType = context.Request.ContentType.Split(';')[0];
            string valueToDeserialize;
            if (parsedContentType == MimeTypes.APPLICATION_X_WWW_FORM_URLENCODED)
            {
                valueToDeserialize = context.Request.Form.ToString();
            }
            else
            {
                using (var stream = context.Request.InputStream)
                {
                    var length = Convert.ToInt32(context.Request.InputStream.Length);
                    var buffer = new byte[length];
                    stream.Read(buffer, 0, length);
                    valueToDeserialize = new UTF8Encoding().GetString(buffer);
                    stream.Close();
                }
            }
            try
            {
                //var deserializedObject = SerializationTable.Serializers[context.Request.ContentType].Deserialize(valueToDeserialize, deserializeAsType);
                var deserializedObject = SerializationTable.Serializers[parsedContentType].Deserialize(valueToDeserialize, deserializeAsType);
                return deserializedObject;
            }
            catch (System.Exception e)
            {
                //TODO: RestHelper.SetServerError(context.Response, string.Format(CultureInfo.CurrentCulture, "There was a problem deserializing to from mime type {0} to type {1}", context.Request.ContentType, deserializeAsType.UnderlyingSystemType.FullName));
                return null;
            }
        }
    }
}